package com.zayats.dal;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.web.client.RestTemplate;

import com.zayats.exceptions.DataAccessDbException;
import com.zayats.exceptions.FamilyNotExistsException;
import com.zayats.model.Family;
import com.zayats.model.User;

public class ApiFamilyRepository {

	private RestTemplate restTemplate;

	String url = "http://api-familyshoplist.herokuapp.com";

	private static final Logger logger = Logger
			.getLogger(ApiFamilyRepository.class);

	@Autowired
	public void setRestTemplate(RestTemplate restTemplate) {
		this.restTemplate = restTemplate;
	}

	public boolean createFamily(String name, String username)
			throws DataAccessDbException {
		logger.info("Go to api: add family");
		List<Boolean> result = new ArrayList<Boolean>();
		result = restTemplate.getForObject(url + "/home/families/add/" + name
				+ "/" + username, List.class);
		return result.get(0);
	}

	public List<Family> getFamiliesForUser(String username) {
		logger.info("Go to api: get families for user");

		return restTemplate.getForObject(url + "/home/families/" + username,
				List.class);
	}

	public boolean deleteUserFromFamily(String username, int familyId) {
		logger.info("Go to api: delete user from family");

		List<Boolean> result = new ArrayList<Boolean>();
		result = restTemplate.getForObject(url + "/home/users/delete/"
				+ username + "/" + familyId, List.class);
		return result.get(0);
	}

	public List<User> getParticipans(int familyId, String username)
			throws EmptyResultDataAccessException, FamilyNotExistsException {
		logger.info("Go to api: get participans of family");

		return restTemplate.getForObject(url + "/home/families/" + familyId
				+ "/" + username, List.class);
	}

	public List<Family> getAllFamiliesForUser(String username) {
		logger.info("Go to api: get all families for user");

		return restTemplate.getForObject(url + "/home/shoplists/" + username,
				List.class);
	}

	public boolean deleteFamily(int familyId) throws DataAccessDbException {
		logger.info("Go to api: delete family");

		List<Boolean> result = new ArrayList<Boolean>();
		result = restTemplate.getForObject(url + "/home/families/delete/"
				+ familyId, List.class);
		return result.get(0);
	}

}
